package com.palandrodev.calsmart.util;

import java.text.DecimalFormat;
import java.text.ParseException;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;

public class NumberTextWatcher implements TextWatcher {

	private DecimalFormat decimalFormat;
	private DecimalFormat decimalFormatNonDecimal;
	private boolean hasFractionalPart;

	private EditText editText;

	public NumberTextWatcher(EditText paramEditTextValue) {
		decimalFormat = new DecimalFormat("#,###.##");
		decimalFormat.setDecimalSeparatorAlwaysShown(true);
		decimalFormatNonDecimal = new DecimalFormat("#,###");
		this.editText = paramEditTextValue;
		hasFractionalPart = false;
	}

	@Override
	public void afterTextChanged(Editable editable) {
		editText.removeTextChangedListener(this);

		try {
			int initialLength, endLength;
			initialLength = editText.getText().length();

			String v = editable.toString().replace(
					String.valueOf(decimalFormat.getDecimalFormatSymbols()
							.getGroupingSeparator()), "");
			Number n = decimalFormat.parse(v);
			int cp = editText.getSelectionStart();
			if (hasFractionalPart) {
				editText.setText(decimalFormat.format(n));
			} else {
				editText.setText(decimalFormatNonDecimal.format(n));
			}
			endLength = editText.getText().length();
			int sel = (cp + (endLength - initialLength));
			if (sel > 0 && sel <= editText.getText().length()) {
				editText.setSelection(sel);
			} else {
				// place cursor at the end?
				editText.setSelection(editText.getText().length() - 1);
			}
		} catch (NumberFormatException nfe) {
			Log.d(Constants.APP_NAME, nfe.getMessage());
		} catch (ParseException e) {
			Log.d(Constants.APP_NAME, e.getMessage());
		}

		editText.addTextChangedListener(this);
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (s.toString().contains(
				String.valueOf(decimalFormat.getDecimalFormatSymbols()
						.getDecimalSeparator()))) {
			hasFractionalPart = true;
		} else {
			hasFractionalPart = false;
		}
	}
}
